package com.tql.pandian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.datasource.annotation.Master;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import com.tql.pandian.entity.*;
import com.tql.pandian.entity.dto.*;
import com.tql.pandian.entity.vo.*;
import com.tql.pandian.mapper.*;
import com.tql.pandian.service.ICommonService;
import com.tql.pandian.service.IPandianCaseService;
import com.tql.pandian.util.PinYinUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PandianCaseService implements IPandianCaseService {

    @Autowired
    private ICommonService commonService;

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private TqlEmpMapper tqlEmpMapper;

    @Autowired
    private TqlPandianCaseEmpMapper tqlPandianCaseEmpMapper;

    @Autowired
    private TqlPandianCaseMapper tqlPandianCaseMapper;

    @Autowired
    private TqlPandianCaseStapMapper tqlPandianCaseStapMapper;

    @Autowired
    private TqlStapBaseEntityMapper stapBaseEntityMapper;

    @Autowired
    private TqlStapTypeMapper tqlStapTypeMapper;

    @Master
    @Override
    public List<TqlEmpEntity> getPanDianStoreMan(String idCard) {
        return tqlEmpMapper.selectEmpList(idCard);
    }

    @Override
    public List<Map> findPanDianPerson() {
        //门店编码
        String deptCode = SecurityUtils.getLoginUser().getSysUser().getDeptCode();

        boolean flag= SecurityUtils.isAdmin(SecurityUtils.getUserId());
        //超级管理员
        if(flag){
            return tqlPandianCaseMapper.selectAllAppUser();
        }

        /*if (StringUtils.isNotEmpty(deptCode)){
            List<Map> maps = commonMapper.selectDeptCollection(deptCode);
            if (maps.size() > 0){
                return tqlPandianCaseMapper.selectPanDianPerson(maps.stream().map(t->(Long) t.get("dept_id")).collect(Collectors.toList()));
            }
        }*/
        return tqlPandianCaseMapper.selectStageMan(deptCode);
    }

    @Override
    public List<TsqStapBaseEntity> getContainMaterial(MaterialCaseDTO materialCaseDTO) {
        QueryWrapper<TsqStapBaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("onshelf","上架");
        //菜品类编码（不包括原材料）
        if (StringUtils.isNotEmpty(materialCaseDTO.getStapTypeCode()) && !materialCaseDTO.getStapTypeCode().equals("1")){
            wrapper.apply("stap_code like {0}",  materialCaseDTO.getStapTypeCode() + "%");
        }
        if (StringUtils.isNotEmpty(materialCaseDTO.getMaterialName())){
            wrapper.apply("stap_name like {0}",  "%"+materialCaseDTO.getMaterialName() + "%");
        }

        PageHelper.startPage(materialCaseDTO.getPageNum(),materialCaseDTO.getPageSize());
        PageInfo pageInfo = new PageInfo(stapBaseEntityMapper.selectList(wrapper));
        return pageInfo.getList();
    }

    /**
     * BU101001001200207
     * 0：半成品，1：成品
     * @param materialCaseDTO
     * @return
     */
    @Override
    public List<SemiMaterialVo> getSemiMaterial(MaterialCaseDTO materialCaseDTO) {
        return stapBaseEntityMapper.getSemiMaterial(materialCaseDTO);
    }

    @Override
    public List<TqlStapTypeEntity> getStapType() {
        QueryWrapper<TqlStapTypeEntity> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("id");
        return tqlStapTypeMapper.selectList(wrapper);
    }

    @Override
    public List<TqlPandianCaseStapEntity> findCaseStap(Long caseId) {
        QueryWrapper<TqlPandianCaseStapEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("case_id",caseId);
        return tqlPandianCaseStapMapper.selectList(wrapper);
    }

    /**
     * 新增库位
     * @param tqlPandianCaseDTO
     * @return
     */
    @Override
    @Transactional
    public int savePandianCase(TqlPandianCaseDTO tqlPandianCaseDTO) {
        LoginUser loginUser= SecurityUtils.getLoginUser();
        //盘点库位表
        TqlPandianCaseEntity entity = new TqlPandianCaseEntity();
        entity.setCaseName(tqlPandianCaseDTO.getCaseName());
        String caseCode = "CBK"+tqlPandianCaseDTO.getDeptCode()+PinYinUtil.getPinyin(tqlPandianCaseDTO.getEmpName());
        entity.setCaseCode(caseCode);
        entity.setDeptCode(tqlPandianCaseDTO.getDeptCode());
        entity.setDeptName(tqlPandianCaseDTO.getDeptName());
        entity.setShopCode(loginUser.getSysUser().getDeptCode());
        entity.setShopName(loginUser.getSysUser().getDept().getDeptName());
        entity.setDel("0");
        entity.setCreator(SecurityUtils.getUserId());
        entity.setCreateBy(SecurityUtils.getUsername());
        int a = tqlPandianCaseMapper.insertPandianCase(entity);

        //盘点库位盘点人关系表
        TqlPandianCaseEmpEntity tqlPandianCaseEmpEntity = new TqlPandianCaseEmpEntity();
        tqlPandianCaseEmpEntity.setCaseId(entity.getId());
        tqlPandianCaseEmpEntity.setEmpFnumber(tqlPandianCaseDTO.getEmpFnumber());
        tqlPandianCaseEmpEntity.setEmpPhone(tqlPandianCaseDTO.getEmpPhone());
        tqlPandianCaseEmpEntity.setEmpName(tqlPandianCaseDTO.getEmpName());
        tqlPandianCaseEmpEntity.setDel("0");
        tqlPandianCaseEmpEntity.setCreator(SecurityUtils.getUserId());
        tqlPandianCaseEmpEntity.setCreateBy(SecurityUtils.getUsername());
        tqlPandianCaseEmpEntity.setCreateTime(new Date());
        int b = tqlPandianCaseEmpMapper.insertPandianCaseEmp(tqlPandianCaseEmpEntity);

        //盘点库位物料关系表
        List<TqlPandianCaseStapEntity> tqlPandianCaseStapEntityList = new ArrayList<>();
        tqlPandianCaseDTO.getTqlPandianCaseStapDTOList().forEach(t->{
            TqlPandianCaseStapEntity tqlPandianCaseStapEntity = new TqlPandianCaseStapEntity();
            tqlPandianCaseStapEntity.setCaseId(entity.getId());
            tqlPandianCaseStapEntity.setSemiType(t.getSemiType());
            tqlPandianCaseStapEntity.setStapCode(t.getStapCode());
            tqlPandianCaseStapEntity.setStapName(t.getStapName());

            tqlPandianCaseStapEntity.setStapTypeCode(t.getStapTypeCode());
            tqlPandianCaseStapEntity.setStapTypeName(t.getStapTypeName());
            tqlPandianCaseStapEntity.setDel("0");
            tqlPandianCaseStapEntity.setCreator(SecurityUtils.getUserId());
            tqlPandianCaseStapEntity.setCreateBy(SecurityUtils.getUsername());
            tqlPandianCaseStapEntity.setCreateTime(new Date());
            tqlPandianCaseStapEntityList.add(tqlPandianCaseStapEntity);
        });
        int c = tqlPandianCaseStapMapper.batchInsertPandianCaseStap(tqlPandianCaseStapEntityList);
        return a+b+c;
    }

    /**
     * 修改
     * @param id
     * @return
     */
    @Override
    public CaseVo getPandianCaseById(Long id) {

       List<CaseStapAndMaterialTransUnit> list= tqlPandianCaseMapper.getPandianCaseById(id);
        CaseAndEmpVo entity=tqlPandianCaseEmpMapper.selectEmpAndDeptCode(id);
        CaseVo vo=new CaseVo();
        vo.setStapUnits(list);
        vo.setCaseEmpEntity(entity);
       return vo;

/**
 * select cs.stap_code,cs.stap_name,cs.stap_type_code,cs.stap_type_name,
 * tu.FConvertDenominator,
 * tu.FCurrentUnitIdFName,
 * tu.FCurrentUnitIdFNumber,
 * tu.FConvertNumerator,
 * tu.FDestUnitIdfnumber,
 * tu.FDestUnitIdfname,
 * tu.FMaterialIdFspecification
 *  from tql_pandian_case_stap cs
 * left join tql_material_trans_unit tu on cs.stap_code=tu.FMaterialIdfnumber
 * where cs.case_id=60
 */


//        PandianCaseMainVo pandianCaseMainVo = new PandianCaseMainVo();
//        pandianCaseMainVo.setTqlPandianCaseEntity(tqlPandianCaseMapper.selectById(id));
//        QueryWrapper<TqlPandianCaseEmpEntity> empWrapper = new QueryWrapper<>();
//        empWrapper.eq("case_id",id);
//        pandianCaseMainVo.setTqlPandianCaseEmpEntity(tqlPandianCaseEmpMapper.selectOne(empWrapper));
//        QueryWrapper<TqlPandianCaseStapEntity> stapWrapper = new QueryWrapper<>();
//        stapWrapper.eq("case_id",id);
//        List<TqlPandianCaseStapEntity> list=tqlPandianCaseStapMapper.selectList(stapWrapper);
//        List<PandianVo> list1;
//        if(!CollectionUtils.isEmpty(list))
//        {
//            list1=new ArrayList<>();
//            for (TqlPandianCaseStapEntity each:list) {
//
//            }
//        }
//
//
//        pandianCaseMainVo.setTqlPandianCaseStapEntityList(list);
//
//
//        return pandianCaseMainVo;
    }

    @Override
    @Transactional
    public int updatePandianCase(TqlPandianCaseDTO tqlPandianCaseDTO) {

        //盘点库位表
        LoginUser loginUser= SecurityUtils.getLoginUser();
        TqlPandianCaseEntity entity = new TqlPandianCaseEntity();
        entity.setCaseName(tqlPandianCaseDTO.getCaseName());
        entity.setId(tqlPandianCaseDTO.getId());
        String caseCode = "CBK"+tqlPandianCaseDTO.getDeptCode()+PinYinUtil.getPinyin(tqlPandianCaseDTO.getEmpName());
        entity.setCaseCode(caseCode);
        entity.setDeptCode(tqlPandianCaseDTO.getDeptCode());
        entity.setDeptName(tqlPandianCaseDTO.getDeptName());
        entity.setShopCode(loginUser.getSysUser().getDept().getDeptCode());
        entity.setShopName(loginUser.getSysUser().getDept().getDeptName());
        int a = tqlPandianCaseMapper.updateById(entity);

        //盘点库位盘点人关系表
        TqlPandianCaseEmpEntity tqlPandianCaseEmpEntity = new TqlPandianCaseEmpEntity();
        tqlPandianCaseEmpEntity.setEmpFnumber(tqlPandianCaseDTO.getEmpFnumber());
        tqlPandianCaseEmpEntity.setEmpPhone(tqlPandianCaseDTO.getEmpPhone());
        QueryWrapper<TqlPandianCaseEmpEntity> empWrapper = new QueryWrapper<>();
        empWrapper.eq("case_id",tqlPandianCaseDTO.getId());
        int b = tqlPandianCaseEmpMapper.update(tqlPandianCaseEmpEntity,empWrapper);


        //盘点库位物料关系表 先删除，再插入

//        Long caseId=tqlPandianCaseDTO.getId();
        //当前库位
//        List<CaseStapAndMaterialTransUnit> list= tqlPandianCaseMapper.getPandianCaseById(caseId);
//
//        List<TqlPandianCaseStapDTO>  tt=tqlPandianCaseDTO.getTqlPandianCaseStapDTOList();
//



//
//
//        QueryWrapper<TqlPandianCaseStapEntity> delWrapper = new QueryWrapper<>();
//        delWrapper.eq("case_id",tqlPandianCaseDTO.getId());
//        tqlPandianCaseStapMapper.delete(delWrapper);
        List<TqlPandianCaseStapDTO> list= tqlPandianCaseDTO.getTqlPandianCaseStapDTOList();
        if(!CollectionUtils.isEmpty(list)) {
            List<TqlPandianCaseStapEntity> list1 = new ArrayList<>();
            list.forEach(t -> {
                TqlPandianCaseStapEntity tqlPandianCaseStapEntity = new TqlPandianCaseStapEntity();
                tqlPandianCaseStapEntity.setCaseId(tqlPandianCaseDTO.getId());

                tqlPandianCaseStapEntity.setSemiType(null==t.getSemiType()?0:t.getSemiType());
                tqlPandianCaseStapEntity.setStapCode(t.getStapCode());
                tqlPandianCaseStapEntity.setStapName(t.getStapName());
                tqlPandianCaseStapEntity.setStapTypeCode(t.getStapTypeCode());
                tqlPandianCaseStapEntity.setStapTypeName(t.getStapTypeName());
                tqlPandianCaseStapEntity.setDel("0");
                tqlPandianCaseStapEntity.setCreator(SecurityUtils.getUserId());
                tqlPandianCaseStapEntity.setCreateBy(SecurityUtils.getUsername());
                tqlPandianCaseStapEntity.setCreateTime(new Date());
                list1.add(tqlPandianCaseStapEntity);
            });
            if (!CollectionUtils.isEmpty(list1)) {
                int c = tqlPandianCaseStapMapper.batchInsertPandianCaseStap(list1);
            }
        }


       List<CaseStapAndMaterialTransUnit> delList1= tqlPandianCaseDTO.getDelList();
        if(!CollectionUtils.isEmpty(delList1))
        {
            Long[] delList = delList1.stream()
                    .map(e -> Long.parseLong(e.getId()))
                    .toArray(Long[]::new);

            tqlPandianCaseStapMapper.delCaseStapById(delList);
        }

        return a+b;
    }

    @Override
    public List<PanDianCaseVo> queryPanDianCase(PanDianCaseDTO panDianCaseDTO) {
        return tqlPandianCaseMapper.selectPanDianCaseMain(panDianCaseDTO);
    }

    @Override
    public List<TeamGroupVO> getTeamGroup() {
        boolean flag= SecurityUtils.isAdmin(SecurityUtils.getUserId());
        if (flag){
            return tqlPandianCaseMapper.selectTeamGroup(null);
        }
        return tqlPandianCaseMapper.selectTeamGroup(SecurityUtils.getLoginUser().getSysUser().getDeptCode());
    }

    @Override
    public List<TqlPandianCaseStapDTO> getStapByCaseId(Long pid) {
        return tqlPandianCaseMapper.getStapByCaseId(pid);
    }

}
